react怎么实现点击隐藏显示-世界速读

来源:php中文网 | 2023-01-06 10:03:35 |


(相关资料图)

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react怎么实现点击隐藏显示?

react中元素的显示和隐藏方式的使用

在react中,我们有常用的有四种方式来显示元素的显示和隐藏,和vue不同,vue中我们使用v-if或v-show来显示元素的隐藏和显示

下面分别介绍一下在react中隐藏和显示元素的方法

第一种:用style来显示隐藏

<script type="text/babel">class App extends React.Component {    state={        isShow:false,    }    check=()=>{        this.setState({            isShow:!this.state.isShow        })    }  render() {    return (      <div>        {/*第一种方式,用style来显示隐藏*/}        <button style={{display:this.state.isShow?"block":"none"}}>张云龙</button>        <button style={{display:this.state.isShow?"none":"block"}}>秦霄贤</button>        <button onClick={this.check}>点击切换</button>      </div>    )  }}ReactDOM.render(<App/>,document.getElementById("root"))

block表示显示,none表示隐藏

第二种:用三元运算符

<script type="text/babel">class App extends React.Component {    state={        isShow:false,    }    check=()=>{        this.setState({            isShow:!this.state.isShow        })    }  render() {    return (      <div>        {/*第二种方法,用三元运算符*/}            {            this.state.isShow?(<div>秦霄贤</div>):(<div>张云龙</div>)            }        <button onClick={this.check}>点击切换</button>      </div>    )  }}ReactDOM.render(<App/>,document.getElementById("root"))

第三种:通过短路逻辑进行元素显隐

<script type="text/babel">class App extends React.Component {    state={        isShow:false,    }    check=()=>{        this.setState({            isShow:!this.state.isShow        })    }  render() {    return (      <div>        {/*第三种方式*/}          {            this.state.isShow && <div>秦霄贤</div>        }        {            !this.state.isShow && <div>张云龙</div>        }        <button onClick={this.check}>点击切换</button>      </div>    )  }}ReactDOM.render(<App/>,document.getElementById("root"))

第四种:函数形式

<script type="text/babel">class App extends React.Component {    state={        isShow:false,        love:"秦霄贤"    }    check=()=>{        this.setState({            isShow:!this.state.isShow        })    }    loves=(key)=>{        switch(key){            case "秦霄贤":                return <div>秦霄贤</div>            case "张云龙":                return <div>张云龙</div>        }       }  render() {    let ok=this.loves(this.state.love)    return (      <div>        {/*第四种函数形式*/}        {ok}        <button onClick={this.check}>点击切换</button>      </div>    )  }}ReactDOM.render(<App/>,document.getElementById("root"))

推荐学习:《react视频教程》

以上就是react怎么实现点击隐藏显示的详细内容,更多请关注php中文网其它相关文章!

关键词: React